const Router = require('koa-router');
const cors = require('koa2-cors');
const bodyParser = require('koa-bodyparser');
const { findFiles,registerRouter,resolveToken} = require('../tools');
const {Result,user} = require('../models');

async function validateToken(ctx,next){
    console.log(ctx.path,ctx.method);
    if(ctx.path==='/login' || ctx.path === '/user' && ctx.method == 'POST')return next();
    let authHeader = ctx.request.header.authorization;
    if (!authHeader) return ctx.body = JSON.stringify(new Result(501,null,'缺少token',false));
    let token = authHeader.split(" ")[1];
    if (!token) return ctx.body = JSON.stringify(new Result(501,token,'缺少token',false));
    try{
        let { id,username,timeStamp } = resolveToken(token);
        let userInfo = await user.findByPk(id);
        if(userInfo.dataValues.token !== token){
            return ctx.body = JSON.stringify(new Result(502,token,'token过期了',false));
        }
        ctx.state.userInfo = {
            id,username,timeStamp
        }
        try{
            await next();
        }catch(ers){
            console.error("中间件出现异常",ers);
            return ctx.body = new Result(599,ers,'在某个中间件中出现了异常',false)
        }
    }catch(err){
        console.log(err);
        return ctx.body = JSON.stringify(new Result(502,token,'token非法',false));
    }
}

async function endCtx(ctx,next){
    console.log("什么也没有的地方");
    ctx.body = `<h1>来到了什么也没有的地方</h1>`
}

function fn(app){
    const files = findFiles();
    const router = new Router();
    registerRouter(files,router);
    app.use(cors());
    app.use(bodyParser());
    app.use(validateToken);
    app.use(router.routes());
    app.use(endCtx)
}

module.exports = fn;